package website.lucaswork.survey.mvc.validators;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.context.SecurityContextHolder;
import website.lucaswork.survey.core.entities.User;
import website.lucaswork.survey.core.services.SurveyService;

import javax.validation.Constraint;
import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;
import javax.validation.Payload;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;

@Retention(RetentionPolicy.RUNTIME)
@Constraint(validatedBy = UniqueSurveyTitlePerUser.UniqueSurveyTitlePerUserValidator.class)
@Target({ElementType.FIELD, ElementType.METHOD})
public @interface UniqueSurveyTitlePerUser {
    String message() default "You can not use this title because already have a survey with the same title";

    Class<?>[] groups() default {};

    Class<? extends Payload>[] payload() default {};

    public class UniqueSurveyTitlePerUserValidator implements ConstraintValidator<UniqueSurveyTitlePerUser, String> {

        @Autowired
        SurveyService surveyService;

        @Override
        public void initialize(UniqueSurveyTitlePerUser constraintAnnotation) {
        }

        @Override
        public boolean isValid(String value, ConstraintValidatorContext context) {
            if (StringUtils.isEmpty(value)) {
                return true;
            }
            User currentUser = (User) SecurityContextHolder.getContext().getAuthentication().getPrincipal();
            return surveyService.getSurveyByTitleAndUser(value, currentUser) == null;
        }
    }
}
